import { connect } from 'umi';
import { useState, useEffect } from 'react';
import styles from './index.less';
import { Table, Radio, Select, Tooltip, InputNumber } from 'antd';
import { tableLocale } from '@/tool/components/PageEmpty';
import { question } from '@/assets';
import { TRADE_STRATEGY, SUBMIT_TYPE } from '../../constant/enums';
import { getChangeTradeStrategyPayload, get24HourLimitList } from '../../utils';

const { Column, ColumnGroup } = Table;
const { Option } = Select;

function TradeTable({
  editPermission,
  currentProgramHourOrderList,
  selectedRowKeys,
  currentUnitList,
  powerLimitInfo,
  priceLimitInfo,
  currentSequenceId,
  dispatch,
}) {
  const [limitList, setLimitList] = useState({});

  // 当前方案选择场站、限额、限价信息变动时，刷新限额信息
  useEffect(
    () =>
      setLimitList(
        get24HourLimitList(powerLimitInfo, currentUnitList, priceLimitInfo[currentSequenceId]),
      ),
    [currentUnitList, powerLimitInfo, priceLimitInfo],
  );

  /**
   * 修改申报类型
   * @param {*} submitType
   * @param {*} modifyHourOrder
   * @returns
   */
  const changeSubmitType = (submitType, hourOrder) =>
    dispatch({
      type: 'rollingBatch/modifyProgramInfoContent',
      payload: { modifyInfo: { [hourOrder]: { submitType, power: 0 } } },
    });

  /**
   * 修改申报电量
   * @param {*} power
   * @param {*} modifyHourOrder
   * @returns
   */
  const changePower = (power, hourOrder) =>
    dispatch({
      type: 'rollingBatch/modifyProgramInfoContent',
      payload: { modifyInfo: { [hourOrder]: { power } } },
    });

  /**
   * 修改申报电价
   * @param {*} price
   * @param {*} modifyHourOrder
   * @returns
   */
  const changePrice = (price, hourOrder) =>
    dispatch({
      type: 'rollingBatch/modifyProgramInfoContent',
      payload: { modifyInfo: { [hourOrder]: { price } } },
    });

  /**
   * 修改交易方向
   * @param {*} value
   * @param {*} index
   */
  const changeTradeStrategy = (tradeStrategyType, hourOrder) =>
    dispatch({
      type: 'rollingBatch/modifyProgramInfoContent',
      payload: {
        modifyInfo: getChangeTradeStrategyPayload(
          [currentProgramHourOrderList.find((item) => item.hourOrder === hourOrder)],
          tradeStrategyType,
        ),
      },
    });

  /**  table渲染方法 **/

  /**
   * table的行classname渲染
   * @param {*} param0
   * @returns
   */
  const tableRowClassRender = ({ tradeStrategyType }) => {
    let { SELL, BUY, NOT_DEAL, NO_STRATEGY } = TRADE_STRATEGY;
    switch (tradeStrategyType) {
      case SELL:
        return 'red';
      case BUY:
        return 'green';
      case NOT_DEAL:
        return 'yellow';
      case NO_STRATEGY:
        return 'gray';
    }
  };

  // 交易方向
  const tradeStrategyRowTitleRender = () => (
    <div>
      <div>
        <span>交易方向</span>
        <Tooltip
          placement="bottom"
          title={
            <span>
              交易策略分为四种，分别代表“卖出”(红色)、“不交易”(黄色)、“买入”(绿色)、“无策略”(灰色)。
              <br />
              其中“不交易”代表该时点的策略是“不想参与交易”，如申报时交易中心已有挂单，则会做撤单操作；“无策略”代表方案不对该时点设定策略，申报时不改变交易平台当前申报状态，请注意区分二者。
            </span>
          }
        >
          <img className={styles.icon} src={question} />
        </Tooltip>
      </div>
      <div>(卖出、不交易、买入、无策略)</div>
    </div>
  );
  const tradeStrategyRowContentRender = (value, record, index) => (
    <div className={styles.tradeStrategy}>
      <Radio.Group
        className={styles.radioGroup}
        value={value}
        onChange={(e) => {
          changeTradeStrategy(e.target.value, index + 1);
        }}
      >
        {/* todo 可以用遍历解决 */}
        <Radio.Button className={`${styles.radio} red`} value={TRADE_STRATEGY.SELL}>
          <div className="circle" />
        </Radio.Button>
        <Radio.Button className={`${styles.radio} yellow`} value={TRADE_STRATEGY.NOT_DEAL}>
          <div className="circle" />
        </Radio.Button>
        <Radio.Button className={`${styles.radio} green`} value={TRADE_STRATEGY.BUY}>
          <div className="circle" />
        </Radio.Button>
        <Radio.Button className={`${styles.radio} gray`} value={TRADE_STRATEGY.NO_STRATEGY}>
          <div className="circle" />
        </Radio.Button>
      </Radio.Group>
    </div>
  );

  // 最高限价
  const upperPriceLimitRowContentRender = (value, record, index) =>
    limitList[index]?.upperPriceLimit.toFixed(2);
  const upperPriceLimitRowTitleRender = () => (
    <div>
      <div>最高限价</div>
      <div>(元/MWh)</div>
    </div>
  );

  // 最低限价
  const lowerPriceLimitRowContentRender = (value, record, index) =>
    limitList[index]?.lowerPriceLimit.toFixed(2);
  const lowerPriceLimitRowTitleRender = () => (
    <div>
      <div>最低限价</div>
      <div>(元/MWh)</div>
    </div>
  );

  // 买入限额
  const buyLimitPowerRowTitleRender = () => (
    <div>
      <div>
        <span>买入限额</span>
        <Tooltip
          placement="bottom"
          title="展示方案全部交易单元在各个时点的买入限额总和。该限额仅做展示用，申报电量的限额控制仍以各单元限额为准。"
        >
          <img className={styles.icon} src={question} />
        </Tooltip>
      </div>
      <div>(MWh)</div>
    </div>
  );
  const buyLimitPowerRowContentRender = (value, record, index) =>
    editPermission ? limitList[index]?.buyLimit.toFixed(3) : record.buyPowerLimit;

  // 卖出限额
  const sellLimitPowerRowTitleRender = () => (
    <div>
      <div>
        <span>卖出限额</span>
        <Tooltip
          placement="bottom"
          title="展示方案全部交易单元在各个时点的卖出限额总和。该限额仅做展示用，申报电量的限额控制仍以各单元限额为准。"
        >
          <img className={styles.icon} src={question} />
        </Tooltip>
      </div>
      <div>(MWh)</div>
    </div>
  );
  const sellLimitPowerRowContentRender = (value, record, index) =>
    editPermission ? limitList[index]?.sellLimit.toFixed(3) : record.sellPowerLimit;

  // 申报电量
  const powerRowGroupTitleRender = () => (
    <>
      <span>申报电量</span>
      <Tooltip
        placement="bottom"
        title="该申报电量为针对每个交易单元的时点申报值，非多交易单元总申报量。请注意与限额数据做区分"
      >
        <img className={styles.icon} src={question} />
      </Tooltip>
    </>
  );
  const powerRatioSelectRowContentRender = (submitType, record, index) => {
    let radioChecked = submitType === SUBMIT_TYPE.FIXED;
    return (
      <div className={styles.submitType}>
        <Radio
          checked={!radioChecked}
          onChange={() => changeSubmitType(SUBMIT_TYPE.INSTALLED_CAPACITY, index + 1)}
        />
        <Select
          value={radioChecked ? SUBMIT_TYPE.INSTALLED_CAPACITY : submitType}
          bordered={false}
          onChange={(type) => changeSubmitType(type, index + 1)}
          disabled={radioChecked}
        >
          <Option className={styles.submitTypeOption} value={SUBMIT_TYPE.INSTALLED_CAPACITY}>
            装机容量
          </Option>
          <Option className={styles.submitTypeOption} value={SUBMIT_TYPE.TRADE_LIMIT}>
            交易限额
          </Option>
        </Select>
      </div>
    );
  };
  const powerRatioValueRowContentRender = (power, record, index) => {
    let inputDisabled = record.submitType === SUBMIT_TYPE.FIXED;
    return (
      <InputNumber
        min={0}
        max={100}
        precision={0}
        className={styles.input}
        value={inputDisabled ? 0 : power * 100}
        onChange={(value) => {
          changePower(value / 100, index + 1);
        }}
        disabled={inputDisabled}
      />
    );
  };
  const powerFixedValueRowContentRender = (text, record, index) => (
    <div className={styles.submitType}>
      <Radio
        checked={text === SUBMIT_TYPE.FIXED}
        onChange={() => changeSubmitType(SUBMIT_TYPE.FIXED, index + 1)}
      />
      <InputNumber
        min={0}
        precision={3}
        className={styles.input}
        value={text === SUBMIT_TYPE.FIXED ? record.power : 0}
        onChange={(value) => {
          changePower(value, index + 1);
        }}
        disabled={
          record.submitType === SUBMIT_TYPE.INSTALLED_CAPACITY ||
          record.submitType === SUBMIT_TYPE.TRADE_LIMIT
        }
      />
    </div>
  );

  // 申报电价
  const priceRowTitleRender = () => (
    <div>
      <div>申报电价</div>
      <div>(元/MWh)</div>
    </div>
  );
  const priceRowContentRender = (text, record, index) => (
    <InputNumber
      min={limitList[index]?.lowerPriceLimit}
      max={limitList[index]?.upperPriceLimit}
      precision={2}
      className={styles.input}
      value={text}
      onChange={(value) => {
        changePrice(value, index + 1);
      }}
    />
  );

  const tableRowSelection = () => ({
    type: 'checkbox',
    selectedRowKeys,
    onChange: (selectedRowKeys) =>
      dispatch({ type: 'rollingBatch/setSelectedRowKeys', payload: selectedRowKeys }),
  });
  return (
    <Table
      className={styles.tradeTable}
      dataSource={currentProgramHourOrderList || []}
      pagination={false}
      rowSelection={tableRowSelection()}
      bordered={true}
      rowKey="hourOrder"
      locale={tableLocale}
      scroll={{ x: 1750 }}
      rowClassName={tableRowClassRender}
    >
      {/* 时段信息 */}
      <Column
        align="center"
        title="时点"
        dataIndex="hourOrder"
        key="hourOrder"
        fixed="left"
        width={60}
      />
      {/* 交易策略 */}
      <Column
        align="center"
        fixed="left"
        width={200}
        title={tradeStrategyRowTitleRender()}
        dataIndex="tradeStrategyType"
        key="tradeStrategyType"
        render={tradeStrategyRowContentRender}
      />
      {/* 最高限价 */}
      <Column
        align="center"
        title={upperPriceLimitRowTitleRender()}
        render={upperPriceLimitRowContentRender}
      />
      {/* 最低限价 */}
      <Column
        align="center"
        title={lowerPriceLimitRowTitleRender()}
        render={lowerPriceLimitRowContentRender}
      />
      {/* 买入限额 */}
      <Column
        align="center"
        title={buyLimitPowerRowTitleRender()}
        render={buyLimitPowerRowContentRender}
      />
      {/* 卖出限额 */}
      <Column
        align="center"
        title={sellLimitPowerRowTitleRender()}
        render={sellLimitPowerRowContentRender}
      />
      <ColumnGroup title={powerRowGroupTitleRender()}>
        {/* 参考值 */}
        <Column
          align="center"
          title="参考值"
          dataIndex="submitType"
          key="submitType"
          render={powerRatioSelectRowContentRender}
        />
        {/* 比例 */}
        <Column
          align="center"
          title="比例(%)"
          dataIndex="power"
          key="power"
          render={powerRatioValueRowContentRender}
        />
        {/* 固定值 */}
        <Column
          align="center"
          title="固定值(MWh)"
          dataIndex="submitType"
          key="submitType"
          render={powerFixedValueRowContentRender}
        />
      </ColumnGroup>
      {/* 电价 */}
      <Column
        align="center"
        title={priceRowTitleRender()}
        dataIndex="price"
        key="price"
        render={priceRowContentRender}
      />
    </Table>
  );
}

export default connect(
  ({
    rollingBatch: {
      currentProgramPermission: { modify: editPermission },
      currentProgramHourOrderList,
      selectedRowKeys,
      priceLimitInfo,
      powerLimitInfo,
      currentUnitList,
      unitPowerLimitList,
      globalSequence: {
        current: { tradeSequenceId: currentSequenceId },
      },
    },
  }) => ({
    editPermission,
    currentProgramHourOrderList,
    selectedRowKeys,
    currentUnitList,
    unitPowerLimitList,
    priceLimitInfo,
    powerLimitInfo,
    currentSequenceId,
  }),
)(TradeTable);
